﻿//-----------------------------------------------------------------------
// <copyright file="SharedLock.cs" author="Artak Mkrtchyan">
//     Creative Commons - GNU General Public License (http://creativecommons.org/licenses/GPL/2.0/
// </copyright>
// <author>Artak Mkrtchyan</author>
// <email>mkArtak@gmail.com</email>
// <date>11/08/2012</date>
//-----------------------------------------------------------------------

using System;
using System.Runtime.ConstrainedExecution;
using System.Threading;

namespace ConsoleHoster.Common.Utilities.Threading
{
	public sealed class SharedLock : CriticalFinalizerObject, IDisposable
	{
		private readonly Object sharedLock;
		private bool lockAquired = false;
		private readonly ILogger logger;

		public SharedLock(Object argObjectToLock, ILogger argLogger)
		{
			this.sharedLock = argObjectToLock;
			this.logger = new ComponentLogger("SharedLock", argLogger);
		}

		public void AquireLock()
		{
			if (!this.lockAquired && this.sharedLock != null)
			{
				Monitor.Enter(this.sharedLock);
				this.lockAquired = true;
			}
		}

		public void ReleaseLock()
		{
			if (this.lockAquired)
			{
				try
				{
					Monitor.Exit(this.sharedLock);
				}
				catch (Exception ex)
				{
					this.logger.LogError("Failed to release lock. Details: {0}", ex.ToString());
				}
				this.lockAquired = false;
			}
		}

		public void Dispose()
		{
			this.Dispose(true);
		}

		private void Dispose(bool argDisposing)
		{
			this.ReleaseLock();
		}
	}
}
